package creational.singleton;

/**
 * @ClassName: ThreadSingleton
 * @Description: 线程单例
 * @Author: liu-hao
 * @Date: 2023-03-27 21:44
 * @Version: 1.0
 **/
public class ThreadSingleton {

    // 初始化ThreadLocal方式一
    private static final ThreadLocal<ThreadSingleton> threadLocal = ThreadLocal.withInitial(() -> new ThreadSingleton());

    // 初始化ThreadLocal方式二
    // private static final ThreadLocal<Singleton06> threadLocal = new ThreadLocal<Singleton06>() {
    //     @Override
    //     protected Singleton06 initialValue() {
    //         return new Singleton06();
    //     }
    // };

    private ThreadSingleton() {
    }

    public static ThreadSingleton getInstance() {
        return threadLocal.get();
    }

    // 测试多线程生成对象
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> System.out.println(ThreadSingleton.getInstance())).start();
        }
    }

}
